package my.sso.my_sso_demo01.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class CookieUtil {
    public static final String COOKIE_NAME = "LOGIN_COOKIE";

    /**
     * @param request
     * @param response
     * 获取登录cookie值
     */
    public static String getLoginCookie(HttpServletRequest request, HttpServletResponse response){
        if(request.getCookies()!=null){
            for(Cookie cookie : request.getCookies()){
                String  name = cookie.getName();
                if(COOKIE_NAME.equals(name)){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * @param request
     * @param response
     * @return
     * 设置登录cookie值
     */
    public static String setLoginCookie(HttpServletRequest request, HttpServletResponse response){
        String uuid = UUID.randomUUID().toString();
        Cookie cookie = new Cookie(COOKIE_NAME,uuid);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return  uuid;
    }
}
